package cn.xiaoyaoji.plugin.html;


import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.CharEncoding;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import cn.com.xiaoyaoji.core.common.Constants;
import cn.com.xiaoyaoji.core.plugin.doc.DocExportPlugin;
import cn.com.xiaoyaoji.core.util.AssertUtils;
import cn.com.xiaoyaoji.data.bean.Doc;
import cn.com.xiaoyaoji.data.bean.Project;
import cn.com.xiaoyaoji.service.ProjectService;
import net.sf.json.JSONSerializer;
import net.sf.json.xml.XMLSerializer;

public class htmlExportForCinterface extends DocExportPlugin{
	
	@Override
    public void doExport(String projectId, HttpServletResponse response) throws IOException 
	{
		Project project = ProjectService.instance().getProject(projectId);
		AssertUtils.notNull(project, "项目不存在");
		List<Doc> docs = ProjectService.instance().getProjectDocs(projectId, true);
		String xml = null;
		String htmlString = null;
		List<String> groupnames = new ArrayList<String>();
		List<List<String>> xmList = new ArrayList<List<String>>();
		for (int i = 0; i < docs.size(); i++) 
		{
			List<String> xmls = new ArrayList<String>();
			List<Doc> chiledos = docs.get(i).getChildren();
			String groupname = docs.get(i).getName();
			if (chiledos != null && !chiledos.isEmpty()) 
			{
				for (int k = 0; k < chiledos.size(); k++) 
				{
					String content = chiledos.get(k).getContent();
					if (null == content) 
                    {
                        List<Doc> chiledoss = chiledos.get(k).getChildren();
                        for (int l = 0; l < chiledoss.size(); l++) 
                        {
                            String contents = chiledoss.get(l).getContent();
                            if (!contents.isEmpty()) 
                            {
                                contents = contents.replace("\r", "");
                                contents = contents.replaceAll("\n", "");
                                String[] b = contents.split(",");
                                for (int o = 0; o < b.length; o++) 
                                {

                                    if (b[o].contains("isCLientInterface") && b[o].contains("true")) 
                                    {
                                        try 
                                        {
                                            xml = xmlConvertor(contents);
                                            xmls.add(xml);
                                        } 
                                        catch (Exception e) 
                                        {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                                
                            }
                        }
                    }
					else 
					{
						content = content.replace("\r", "");
						content = content.replaceAll("\n", "");
						String[] a = content.split(",");
						for (int j = 0; j < a.length; j++) 
						{

							if (a[j].contains("isCLientInterface") && a[j].contains("true")) 
							{
								try 
								{
									xml = xmlConvertor(content);
									xmls.add(xml);
								} 
								catch (Exception e) 
								{
									e.printStackTrace();
								}
							}
						}
					}
				}
			} 
			if (xmls.size() > 0)
            {
			    xmList.add(xmls);
			    groupnames.add(groupname);
            }
		}
		DocConvertor convertor = new DocConvertor();
		boolean res = convertor.convert(xmList, groupnames);
		if (!res) {
			System.out.println("convert root folder " + " failed!");
			return;
		}
		htmlString = convertor.toHtmlString();
		XmlConvertor.argsDsfMethodName = "DSF";
		XmlConvertor.argsIsNeedDB = "0";

		String encoding = Constants.UTF8.displayName();
		response.setCharacterEncoding(encoding);
		response.setContentType("application/json;charset=" + encoding);
		PrintWriter writer = response.getWriter();
		//response.setContentLength(htmlString.getBytes().length);
		String fileName = URLEncoder.encode(project.getName(), Charset.forName(CharEncoding.UTF_8).displayName())
				+ ".html";
		response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\";");
		writer.write(htmlString);
		writer.flush();

	}
	
	//content字段转xml
	public static String xmlConvertor(String content) throws Exception
	{
		XMLSerializer xmlSerializer = new XMLSerializer();
		xmlSerializer.setRootName("Interface");
		xmlSerializer.setTypeHintsEnabled(false);
		String xmls = "";
		xmls = xmlSerializer.write(JSONSerializer.toJSON(content));
		
		SAXReader reader = new SAXReader();
		String xml = null;
		XMLWriter writer = null;

		try 
		{
			org.dom4j.Document document = reader.read(new ByteArrayInputStream(xmls.getBytes("UTF-8")));
			if (document != null) 
			{
				StringWriter stringWriter = new StringWriter();
				OutputFormat format = OutputFormat.createPrettyPrint();
				format.setNewLineAfterDeclaration(false);
				writer = new XMLWriter(stringWriter, format);
				writer.write(document);
				writer.flush();
				xml = stringWriter.getBuffer().toString();
			}
		} 
		finally 
		{
			if (writer != null) 
			{
				try 
				{
					writer.close();
				} 
				catch (Exception e) 
				{
					e.printStackTrace();
				}
			}
		}
		return xml;
	}
}
